package cn.tedu._04weibo.filter;

import cn.tedu._04weibo.pojo.vo.UserVO;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;

@Slf4j
@WebFilter(filterName = "weiboFilter", urlPatterns = {"/v1/weibo/insert","/v1/comment/insert"})
public class WeiboFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.debug("进入微博过滤器...");

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        HttpSession session = request.getSession();
        UserVO userVO = (UserVO)session.getAttribute("user");
        if (userVO != null){
            log.debug("用户已登录，放行...");
            filterChain.doFilter(servletRequest, servletResponse);
        } else {
            log.debug("用户未登录，拦截...");
            response.sendRedirect("/login.html");
        }
    }
}
